package com.duolaibei.business.view;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.duolaibei.business.R;
import com.duolaibei.business.api.ApiName;
import com.duolaibei.business.base.BaseActivity;
import com.duolaibei.business.config.Constant;
import com.duolaibei.business.config.DIR;
import com.duolaibei.business.config.Preferences;
import com.duolaibei.business.http.HttpUtils;
import com.duolaibei.business.model.OrderBeanData;
import com.duolaibei.business.model.ResponseResult;
import com.duolaibei.business.utils.AppInfoUtil;
import com.duolaibei.business.utils.BluetoothUtil;
import com.duolaibei.business.utils.CommonUtil;
import com.duolaibei.business.utils.DlbPrintUtil;
import com.duolaibei.business.utils.FragmentManager;
import com.duolaibei.business.utils.GsonUtil;
import com.duolaibei.business.utils.NotificationCheckUtil;
import com.duolaibei.business.utils.NotificationUtils;
import com.duolaibei.business.utils.PlayVoice;
import com.duolaibei.business.utils.PreferenceUtil;
import com.duolaibei.business.utils.SysUtil;
import com.duolaibei.business.utils.inject.Inject;
import com.duolaibei.business.utils.log.LogDebug;
import com.duolaibei.business.view.activity.OrderListActivity;
import com.duolaibei.business.view.dialog.TipDialog;
import com.duolaibei.business.view.fragment.AccountFragment;
import com.duolaibei.business.view.fragment.HomePageFragment;
import com.duolaibei.business.view.fragment.SetupFragment;
import com.duolaibei.business.view.service.DlbIntentService;
import com.duolaibei.business.view.service.DlbPushService;
import com.duolaibei.business.view.service.ScreenReceiver;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.sunflower.FlowerCollector;
import com.igexin.sdk.PushManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

public class MainActivity extends BaseActivity {

    @Inject(R.id.home_page_avatar)
    private ImageView mImageViewOne;
    @Inject(R.id.account_avatar)
    private ImageView mImageViewTwo;
    @Inject(R.id.setup_avatar)
    private ImageView mImageViewThree;

    @Inject(R.id.home_page_text)
    private TextView mTextViewOne;
    @Inject(R.id.account_text)
    private TextView mTextViewTwo;
    @Inject(R.id.setup_text)
    private TextView mTextViewThree;

    @Inject(R.id.main_home_page)
    private RelativeLayout mRelativeHomePage;
    @Inject(R.id.main_account)
    private RelativeLayout mRelativeAccount;
    @Inject(R.id.main_set_up)
    private RelativeLayout mRelativeSetUp;

    private FragmentManager mFragmentManager;
    private HomePageFragment mHomePageFragment;
    private AccountFragment mAccountFragment;
    private SetupFragment mSetupFragment;

    private String uid;
    private String login_id;
    private String login_type;

    private static final int REQUEST_PERMISSION = 0;
    // DemoPushService.class 自定义服务名称, 核心服务
    private Class userPushService = DlbPushService.class;

    private static String TAG = MainActivity.class.getSimpleName();
    // 语音合成对象
    private SpeechSynthesizer mTts;

    public static PowerManager.WakeLock mWakelock;
    public static PowerManager pm;

    private Intent mIntent;

    private ScreenReceiver screenReceiver;

    private String launchIntent;

    @Override
    protected void onGetIntent(Intent intent) {
        super.onGetIntent(intent);
        if (intent != null) {
            uid = intent.getStringExtra(Constant.UID);
            login_id = intent.getStringExtra(Constant.LOGIN_ID);
            login_type = intent.getStringExtra(Constant.LOGIN_TYPE);
        }
    }

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void initViews() {

    }

    @SuppressLint("InvalidWakeLockTag")
    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakelock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
                | PowerManager.SCREEN_DIM_WAKE_LOCK, "WakeLock");
        App.getApp().mainActivity = this;
        mainActivity = this;
        initGetui();
        setOneState();
        initMainFragment();
        mFragmentManager.showFragment(mHomePageFragment);
        getUseInfo();
        intiTts();
        if (CommonUtil.isEmpty(String.valueOf(PreferenceUtil.getParam(Preferences.PRINTNUM, "")))) {
            PreferenceUtil.setParam(Preferences.PRINTNUM, "1");
        }
        PreferenceUtil.setParam(Preferences.ISCONNECTED, "false");
        mIntent = new Intent(getThis(), OrderListActivity.class);
        mIntent.putExtra("order_type", "all");
//        CommonUtil.ignoreBatteryOptimization(getThis());//设置电量白名单
        checkVersonUpdate();//检测更新
//        startService(new Intent(this, DaemonService.class));//开启守护进程
        showMessageTip();
        registerScreenReceiver();
//        new CatchLogThread().start();
        //you have to start the service once.
        launchIntent = String.valueOf(PreferenceUtil.getParam(Preferences.LAUNCHINTENT, ""));
        //收到推送，应用未启动，先启动应用，在移动到后台
        if (!CommonUtil.isEmpty(launchIntent)) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    removeToground();
                    PreferenceUtil.setParam(Preferences.LAUNCHINTENT, "");
                }
            }, 3000);
        }
        //播放无声音乐
        PlayVoice.playVoice(getApplicationContext());
    }

    /**
     * 注册screen状态广播接收器
     */
    private void registerScreenReceiver() {
        screenReceiver = new ScreenReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        registerReceiver(screenReceiver, filter);
    }

    @Override
    protected void onStart() {
        super.onStart();
        String blueMac = String.valueOf(PreferenceUtil.getParam(Preferences.BLUETOOTH, ""));
        if (!CommonUtil.isEmpty(blueMac)) {
            myOpenBlueTooth();
        }
    }

    //打开蓝牙方法
    private void myOpenBlueTooth() {
        // TODO Auto-generated method stub
        BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
        if (ba != null) {// 如果有蓝牙设备
            LogDebug.d("----------如果有蓝牙设备----------");
            if (!ba.isEnabled())// 如果蓝牙没有打开
            {
                /************************
                 * 打开蓝牙方法
                 *
                 * 方法一：有提示信息地打开蓝牙
                 *
                 *************************/
//                Intent intent = new Intent(
//                        BluetoothAdapter.ACTION_REQUEST_ENABLE);
//                startActivity(intent);
                /***********************
                 * 方法二：无提示开启蓝牙
                 * *********************/
                ba.enable();//静默开启蓝牙
                LogDebug.d("----------静默开启蓝牙----------");
            } else {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (BluetoothUtil.connectBlueTooth(getThis())) {
                            PreferenceUtil.setParam(Preferences.ISCONNECTED, "true");
                        }
                    }
                }).start();
            }
        } else {
            Toast.makeText(this, "对不起，您的设备不支持蓝牙", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取用户账号信息
     */
    private void getUseInfo() {
        String loginType = String.valueOf(PreferenceUtil.
                getParam(Preferences.LOGINTYPE, ""));
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", ApiName.USERINFO);
        param.add("uid", String.valueOf(PreferenceUtil.getParam(Preferences.UID, "")));
        param.add("login_type", loginType);
        if (!"merchant".equals(loginType)) {
            param.add("login_id", String.valueOf(PreferenceUtil
                    .getParam(Preferences.LOGINID, "")));
        }
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().url(ApiName.API).params(param)
                .executePost(new HttpUtils.HttpListener() {
                    @Override
                    public void onException(Throwable e) {
                        super.onException(e);
                        if (CommonUtil.isForeground(getThis())) {
                            showToast(getString(R.string.net_state));
                        }
                    }

                    @Override
                    public void onHttpSuccess(String string) {
                        super.onHttpSuccess(string);
                        if (HttpUtils.isJson(string)) {
                            ResponseResult result = GsonUtil.GsonToBean(string, ResponseResult.class);
                            //showToast(result.getInfo());
                        } else {
                            showToast(string);
                        }
                    }
                });
    }

    /**
     * 绑定个推
     *
     * @param cliend_id
     */
    public void sendCliendId(String cliend_id) {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", ApiName.BIND);
        param.add("uid", String.valueOf(PreferenceUtil.getParam(Preferences.UID, "")));
        param.add("clientid", cliend_id);
        param.add("clienttype", "ANDROID");
        param.add("sdktype", "getui");
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().url(ApiName.API).params(param).
                executePost(new HttpUtils.HttpListener() {
                    @Override
                    public void onHttpSuccess(String string) {
                        super.onHttpSuccess(string);
                    }
                });
    }


    /**
     * 初始化个推
     */
    private void initGetui() {
        PackageManager pkgManager = getPackageManager();
        // 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
        boolean sdCardWritePermission = pkgManager.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                getPackageName()) == PackageManager.PERMISSION_GRANTED;
        // read phone state用于获取 imei 设备信息
        boolean phoneSatePermission = pkgManager.checkPermission(Manifest.permission.READ_PHONE_STATE,
                getPackageName()) == PackageManager.PERMISSION_GRANTED;
        if (Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission || !phoneSatePermission) {
            requestPermission();
        } else {
            PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
        }

        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DlbIntentService.class);
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE}, REQUEST_PERMISSION);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION) {
            if ((grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
                PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
            } else {
                PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    /**
     * NotificationCheckUtil
     * 判断消息提醒设置是否打开
     */
    private void showMessageTip() {
        //检测通知开关是否开启
        if (!NotificationCheckUtil.notificationIsOpen(mainActivity)) {
            mainActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showConfirm("提示", "    消息提醒已关闭，你将收不到应用通知和活动提醒。是否打开？");
                }
            });
        }
    }

    private int count = 1;
    MainActivity mainActivity;

    public void sendNotification(String content) {
        new MyThread(content).start();
    }

    private class MyThread extends Thread {
        private String content;

        MyThread(String content) {
            this.content = content;
        }

        @SuppressLint("WakelockTimeout")
        @Override
        public void run() {
            mWakelock.acquire(10*60*1000L /*10 minutes*/);//强制点亮
            mWakelock.release();//取消强制点亮
            count++;
            //状态栏显示通知内容
            NotificationUtils.createNotif(getThis(),
                    R.mipmap.getui_icon,
                    "订单交易成功提醒",
                    content,
                    mIntent,
                    count);
            //播放声音
            if ("true".equals(PreferenceUtil.getParam(Preferences.VOICE, "true"))) {
                liveSound(content.substring(content.indexOf(",") + 3));
            }
            //通过订单号获取订单详情
            getOrderData(content.substring(3, content.indexOf(",")));
        }
    }

    /**
     * 获取订单信息
     *
     * @param orderNum
     */
    private void getOrderData(String orderNum) {
        String loginType = String.valueOf(PreferenceUtil.getParam(Preferences.LOGINTYPE, ""));
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", ApiName.ORDER_DETAIL);
        param.add("uid", String.valueOf(PreferenceUtil.getParam(Preferences.UID, "")));
        param.add("login_type", loginType);
        if (!"merchant".equals(loginType)) {
            param.add("login_id", String.valueOf(PreferenceUtil.getParam(Preferences.LOGINID, "")));
        }
        param.add("out_trade_no", orderNum);
        param.add("sign", param.getMd5String());
        HttpUtils.getInstance().url(ApiName.API).params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                if (CommonUtil.isForeground(getThis())) {
                    showToast(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                if (HttpUtils.isJson(string)) {
                    ResponseResult result = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (result.getStatus() == 1) {
                        final OrderBeanData notesData = GsonUtil.GsonToBean(string, OrderBeanData.class);
                        final OrderBeanData.DataBean dataBean = notesData.getData();//打印数据
                        //打印次数
                        final int printCount = Integer.valueOf(String.valueOf(PreferenceUtil.getParam(Preferences.PRINTNUM, "")));
                        //开始打印
                        try {
                            DlbPrintUtil.printData(getThis(), dataBean,
                                    String.valueOf(dataBean.getOut_trade_no()), printCount);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        showToast(result.getInfo());
                    }
                } else {
                    showToast(string);
                }
            }
        });
    }


    /**
     * 语音播放
     */
    private void liveSound(final String amount) {
        // 移动数据分析，收集开始合成事件
        FlowerCollector.onEvent(getThis(), "tts_play");
        mTts.startSpeaking(String.format("多来贝到账%1$s元", amount), mTtsListener);
    }

    private TipDialog confirmDialog;

    private void showConfirm(String title, String content) {
        if (confirmDialog == null) {
            confirmDialog = new TipDialog(mainActivity);
        }
        confirmDialog.setTitle(title);
        confirmDialog.setContent(content);
        confirmDialog.setCancelable(true);
        confirmDialog.setConfirm("去设置");
        //设置为系统弹窗，任何位置都可以弹出
        //confirmDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
        confirmDialog.show();
        confirmDialog.setListener(new TipDialog.Listener() {
            @Override
            public void onConfirm() {
                super.onConfirm();
                confirmDialog.dismiss();
                AppInfoUtil.showInstalledAppDetails(mainActivity,
                        mainActivity.getPackageName());
            }

            @Override
            public void onDismiss() {
                super.onDismiss();
                confirmDialog.dismiss();
            }
        });
    }

    /**
     * 初始化语音播报
     */
    private void intiTts() {
        // 初始化合成对象
        mTts = SpeechSynthesizer.createSynthesizer(getThis(), mTtsInitListener);
        setParam();
    }

    /**
     * 初始化监听。
     */
    private InitListener mTtsInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            Log.d(TAG, "InitListener init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                Log.d(TAG, "init data fail，errorCode message = " + code);
            } else {
                // 初始化成功，之后可以调用startSpeaking方法
                // 注：有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成，
                // 正确的做法是将onCreate中的startSpeaking调用移至这里
            }
        }
    };

    /**
     * 合成回调监听。
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {

        @Override
        public void onSpeakBegin() {
        }

        @Override
        public void onSpeakPaused() {
        }

        @Override
        public void onSpeakResumed() {
        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos, String info) {
            // 合成进度
//            mPercentForBuffering = percent;
//            showTip(String.format(getString(R.string.tts_toast_format),
//                    mPercentForBuffering, mPercentForPlaying));
        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
            // 播放进度
//            mPercentForPlaying = percent;
//            showTip(String.format(getString(R.string.tts_toast_format),
//                    mPercentForBuffering, mPercentForPlaying));
        }

        @Override
        public void onCompleted(SpeechError error) {
            if (error == null) {
                Log.d(TAG, "play onCompleted");
            } else if (error != null) {
                Log.d(TAG, "play onCompleted：" + error.getPlainDescription(true));
            }
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //		Log.d(TAG, "session id =" + sid);
            //	}
        }
    };

    /**
     * 参数设置
     *
     * @return
     */
    private void setParam() {
        mTts = SpeechSynthesizer.createSynthesizer(getThis(), mTtsInitListener);
        // 清空参数
        mTts.setParameter(SpeechConstant.PARAMS, null);
        // 根据合成引擎设置相应参数
        String engineType = SpeechConstant.TYPE_CLOUD;
        if (engineType.equals(SpeechConstant.TYPE_CLOUD)) {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
            // 设置在线合成发音人
            String voicer = "xiaoyan";
            mTts.setParameter(SpeechConstant.VOICE_NAME, voicer);
            //设置合成语速
            mTts.setParameter(SpeechConstant.SPEED, "18");
            //设置合成音调
            mTts.setParameter(SpeechConstant.PITCH, "50");
            //设置合成音量
            mTts.setParameter(SpeechConstant.VOLUME, "900");
        } else {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
            // 设置本地合成发音人 voicer为空，默认通过语记界面指定发音人。
            mTts.setParameter(SpeechConstant.VOICE_NAME, "");
        }
        //设置播放器音频流类型
        mTts.setParameter(SpeechConstant.STREAM_TYPE, "2");
        // 设置播放合成音频打断音乐播放，默认为true
        mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");
        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH,
                Environment.getExternalStorageDirectory() + "/msc/tts.wav");
    }


    @Override
    protected void onResume() {
        //移动数据统计分析
        FlowerCollector.onResume(getThis());
        FlowerCollector.onPageStart(TAG);
        super.onResume();
    }

    @Override
    protected void onPause() {
        //移动数据统计分析
        FlowerCollector.onPageEnd(TAG);
        FlowerCollector.onPause(getThis());
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mTts) {
            mTts.stopSpeaking();
            // 退出时释放连接
            mTts.destroy();
        }
        if (screenReceiver != null) {
            unregisterReceiver(screenReceiver);
        }
    }


    /**
     * 初始化首页fragment
     */
    private void initMainFragment() {
        mFragmentManager = initFragmentManager(R.id.main_layout);
        Bundle bundle = new Bundle();
        bundle.putString(Constant.UID, uid);
        bundle.putString(Constant.LOGIN_ID, login_id);
        bundle.putString(Constant.LOGIN_TYPE, login_type);
        mHomePageFragment = new HomePageFragment();
        mHomePageFragment.setArguments(bundle);
        mAccountFragment = new AccountFragment();
        mSetupFragment = new SetupFragment();
    }

    @Override
    protected void onSetListener() {
        mRelativeHomePage.setOnClickListener(this);
        mRelativeAccount.setOnClickListener(this);
        mRelativeSetUp.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.main_home_page) {
            setOneState();
            mFragmentManager.showFragment(mHomePageFragment);
        } else if (v.getId() == R.id.main_account) {
            setTwoState();
            mFragmentManager.showFragment(mAccountFragment);
        } else if (v.getId() == R.id.main_set_up) {
            setThreeState();
            mFragmentManager.showFragment(mSetupFragment);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            removeToground();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 捕捉home事件
     */
//    @Override
//    protected void onUserLeaveHint() {
//        super.onUserLeaveHint();
//        removeToground();
//    }

    /**
     * 切换应用到后台/防止华为机型未加入白名单时按返回键回到桌面再锁屏后几秒钟进程被杀
     */
    private void removeToground() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }

    // tab one
    private void setOneState() {
        mTextViewOne.setSelected(true);
        mTextViewTwo.setSelected(false);
        mTextViewThree.setSelected(false);
        mImageViewOne.setSelected(true);
        mImageViewTwo.setSelected(false);
        mImageViewThree.setSelected(false);
    }

    // tab two
    private void setTwoState() {
        mTextViewOne.setSelected(false);
        mTextViewTwo.setSelected(true);
        mTextViewThree.setSelected(false);
        mImageViewOne.setSelected(false);
        mImageViewTwo.setSelected(true);
        mImageViewThree.setSelected(false);
    }

    // tab three
    private void setThreeState() {
        mTextViewOne.setSelected(false);
        mTextViewTwo.setSelected(false);
        mTextViewThree.setSelected(true);
        mImageViewOne.setSelected(false);
        mImageViewTwo.setSelected(false);
        mImageViewThree.setSelected(true);
    }

    private String mApkUrl;//下载地址
    private String mUpdateVersion;//当前版本

    /**
     * 检查版本更新
     */
    public void checkVersonUpdate() {
        final String mCurrentVersion = CommonUtil.getVersionName(App.getApp());
        HttpUtils.RequestParam params = new HttpUtils.RequestParam();
        params.add("method", ApiName.APP_VERSION);
        params.add("clienttype", "ANDROID");
        params.add("sign", params.getMd5String());
        HttpUtils.getInstance().params(params).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                if (CommonUtil.isForeground(getThis())) {
                    showToast(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 1) {
                        try {
                            mApkUrl = new JSONObject(string).getJSONObject("data")
                                    .optString("native_android_download");
                            mUpdateVersion = new JSONObject(string).getJSONObject("data")
                                    .optString("native_android_version");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //是否更新
                        if (!mCurrentVersion.equals(mUpdateVersion)) {
                            File dir = new File(DIR.TEMP_APK);
                            //删除已存在的apk
                            if (dir.exists()) {
                                File[] files = dir.listFiles();
                                for (File file : files) {
                                    if (file.getName().contains(".apk")) {
                                        try {
                                            CommonUtil.deleteFile(file);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                            foundUpdate();
                        }
                    } else {
                        showToast(responseResult.getInfo());
                    }
                }
            }
        });
    }

    private void foundUpdate() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showUpdateTip();
            }
        });
    }

    //下载应用
    private void downLoadApk() {
        HttpUtils.getInstance().loadFile(mApkUrl, new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
            }

            @Override
            public void onResponseProgress(long progress, long total, boolean done) {
                float per = (float) progress / (float) total * (float) 100;
                String pers = String.valueOf(per);
                if (pers.length() > 5) {
                    pers = pers.substring(0, 5);
                }
                final String finalPers = pers;
                showDownProgress("正在下载" + " " + finalPers + "%");
            }

            @Override
            public void onHttpSuccess(byte[] bytes) {
                showDownProgress("准备安装，请稍后");
                String savepath = DIR.TEMP_APK + "/" + mUpdateVersion + ".apk";
                final File file = new File(savepath);
                try {
                    CommonUtil.byte2File(bytes, file.getParent(), file.getName());
                    dismissDownProgress();
                    SysUtil.installApk(App.getApp(), file.getPath());
                } catch (Exception e) {
                    LogDebug.e(e);
                }
            }
        });
    }

    private TipDialog mUpdateTip;

    private void showUpdateTip() {
        if (mUpdateTip == null) {
            mUpdateTip = new TipDialog(getThis());
            mUpdateTip.setContent("发现新版，是否更新？");
            mUpdateTip.setCancle("否");
            mUpdateTip.setConfirm("是");
            mUpdateTip.setCancelable(true);
            mUpdateTip.setListener(new TipDialog.Listener() {
                @Override
                public void onConfirm() {
                    downLoadApk();
                }

                @Override
                public void onDismiss() {
                    super.onDismiss();
                    mUpdateTip.dismiss();
                }
            });
        }
        mUpdateTip.show();
    }

//    private boolean isTesting = true;

//    class CatchLogThread extends Thread {
//        @Override
//        public void run() {
//            Process mLogcatProc = null;
//            BufferedReader reader = null;
//            String line;
//            while (isTesting) {
//                try {
//                    // 获取logcat日志信息
//                    mLogcatProc = Runtime.getRuntime().exec(new String[]{"logcat", "ActivityManager:I *:S"});
//                    reader = new BufferedReader(new InputStreamReader(mLogcatProc.getInputStream()));
//                    while ((line = reader.readLine()) != null) {
//                        if (line.indexOf("android.intent.category.HOME") > 0) {
//                            isTesting = false;
//                            handler.sendMessage(handler.obtainMessage());
//                            Runtime.getRuntime().exec("logcat -c");//删除日志
//                            break;
//                        }
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//    }
//
//    ;
//
//    Handler handler = new Handler() {
//        public void handleMessage(android.os.Message msg) {
//            Log.i(TAG, "Home key press");
//            //do something here
//            removeToground();
//        }
//    };

}
